package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.file.service.impl.OSSAliyunFileStorageService;
import com.heima.model.common.constants.wemedia.WemediaConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    OSSAliyunFileStorageService storageService;


    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Value("${file.oss.profix}")
    private String profix;

    @Value("${file.oss.web-site}")
    private String webSite;



    /**
     * 上传图片接口
     *
     * @param file
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile file) {
        // 1 参数校验
        if (file.isEmpty()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 2 上传到oss
        //原始文件名称
        String originalFilename = file.getOriginalFilename();
        String newFileName = UUID.randomUUID().toString().replace("-", "");
        String fileID = null;
        //文件后缀获取
        String postFix = originalFilename.substring(originalFilename.lastIndexOf("."));
        try {
            fileID = storageService.store(profix, newFileName + postFix,
                    file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
            log.error("WmMaterialServiceImpl file upload error:{}", e);
            CustException.cust(AppHttpCodeEnum.FILE_UPLOAD_ERROR);
        }

        // 3 获取登录用户ID
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }

        //文件信息保存
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setCreatedTime(new Date());
        wmMaterial.setIsCollection(WemediaConstants.IS_COLLECTION);
        wmMaterial.setType(WemediaConstants.PICTURE_TYPE);

        if (StringUtils.isBlank(fileID)) {
            CustException.cust(AppHttpCodeEnum.FILE_UPLOAD_ERROR);
        }
        wmMaterial.setUrl(fileID);
        //当前登录的用户
        wmMaterial.setUserId(user.getId());
        save(wmMaterial);
        //给文件图片加访问的前缀
        wmMaterial.setUrl(webSite + fileID);
        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 素材列表查询
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmMaterialDto dto) {

        // 1 参数校验
        dto.checkParam();
        // 2 执行业务查询
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        // 收藏
        if (dto.getIsCollection()!=null&&dto.getIsCollection()==1){
            wrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        // 当前登录用户的素材
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null){
            CustException.cust(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }

        wrapper.eq(WmMaterial::getUserId,user.getId());

        // 时间倒序

        wrapper.orderByDesc(WmMaterial::getCreatedTime);
        IPage<WmMaterial> pageParam=new Page<>(dto.getPage(),dto.getSize());
        IPage<WmMaterial> resultPage = page(pageParam, wrapper);
        // 处理图片

        List<WmMaterial> records = resultPage.getRecords();
        for (WmMaterial record : records) {
            record.setUrl(webSite+record.getUrl());
        }
        // 3 封装结果

        return new PageResponseResult(dto.getPage(),dto.getSize(),resultPage.getTotal()
                ,resultPage.getRecords());
    }

    /**
     * 删除图片
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult delPicture(Integer id) {
        // 1 参数校验
        if (id==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2 业务处理
        // 判断当前id是否被引用，如果被使用则禁止删除
        WmMaterial wmMaterial = getById(id);
        if (wmMaterial==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        LambdaQueryWrapper<WmNewsMaterial> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmNewsMaterial::getId,id);
        Integer count = wmNewsMaterialMapper.selectCount(wrapper);
        if (count>0){
            CustException.cust(AppHttpCodeEnum.FILE_DELETE_ERROR);
        }
        // 删除图片OSS
        storageService.delete(wmMaterial.getUrl());
        // 删除素材库
        removeById(id);
        // 3 封装结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 收藏与取消收藏
     *
     * @param id
     * @param type
     * @return
     */
    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        //1.检查参数
        if (id==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.更新状态
        //获取当前用户信息
        Integer uid = WmThreadLocalUtils.getUser().getId();
        update(Wrappers.<WmMaterial>lambdaUpdate().set(WmMaterial::getIsCollection,type)
                        .eq(WmMaterial::getId,id)
                        .eq(WmMaterial::getUserId,uid));
        return  ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
